package think.in.java.concurrency.practise.exec7;

/**
 * Created by IntelliJ IDEA.
 * User: Richard
 * Date: 6/15/11
 * Time: 10:36 PM
 * In this class , we will use the threadlocal for simulate the seperate space for each thread , in each thread , it will
 * maintain a ThreadLocal object in current thread .
 * and also , we define a ShareResource as the volatile , so you can see , the object will be used as atom
 */
public class ThreadRunnerWithThreadLocal implements Runnable{
    private static ThreadLocalImpl threadLocal = new ThreadLocalImpl();
    private int selfId = 0 ;
    private volatile ShareResource shareResource;
    private int value = 0;
    private volatile boolean cancel = false;
    public ThreadRunnerWithThreadLocal(int selfId , ShareResource shareResource){
             this.selfId = selfId;
        this.shareResource = shareResource;
    }
    public void run() {
        while(!cancel){
             threadLocal.set(threadLocal.get()+1);
        value = shareResource.increment();
        System.out.println(this);
            Thread.yield();
        }

    }
    public void cancel(){
        this.cancel = true;
    }
    public String toString(){
         return "["+selfId+"]"+"localValue" + threadLocal.get()+":shareValue:"+value;
    }
}
